package com.pan.handle.resp.impl;

import com.pan.entity.HumbleHttpRequest;
import com.pan.entity.HumbleHttpResponse;
import com.pan.handle.resp.ResponseHandle;
import com.pan.handle.resp.config.DefaultHtmlRead;
import com.pan.servlet.MyHumbleContainer;
import com.pan.servlet.MyHumbleServlet;

public class HumbleHttpRespHandle implements ResponseHandle,DefaultHtmlRead {

    private MyHumbleContainer myHumbleContainer;

    public HumbleHttpRespHandle() {
    }

    public HumbleHttpRespHandle(MyHumbleContainer myHumbleContainer) {
        this.myHumbleContainer = myHumbleContainer;
    }

    public void setMyHumbleContainer(MyHumbleContainer myHumbleContainer) {
        this.myHumbleContainer = myHumbleContainer;
    }

    @Override
    public String back(HumbleHttpRequest request){
        MyHumbleServlet myHumbleServlet = myHumbleContainer.get(request.getUrl());
        if (myHumbleServlet == null){
            String result = "HTTP/1.1 404 OK"+"\r\n"+
                    "Content-Type: text/html; charset=utf-8"+"\r\n"+
                    "Server: SimpleHTTPServer"+"\r\n"+
                    "Connection: close"+"\r\n"+
                    "\r\n"+// 返回头和正文之间的空行 This is the Header And Content Null Line
                    ""+get404HtmlString();
            return result;
        }
        String method = request.getMethod();
        HumbleHttpResponse response = new HumbleHttpResponse();
        if (method.equalsIgnoreCase("get")){
            myHumbleServlet.doGet(request,response);
        }else if (method.equalsIgnoreCase("post")){
            myHumbleServlet.doPost(request,response);
        }else if (method.equalsIgnoreCase("put")){
            myHumbleServlet.doPut(request,response);
        }else if (method.equalsIgnoreCase("delete")){
            myHumbleServlet.doDelete(request,response);
        }
        return response.toString();
    }
}
